package com.yyfax.ph.personal.authority.phonechange;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.personal.authority.RSAPresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Title: ChangeNewPhonePresenter Description: Company: YYLending(YouJingPuHui)
 *
 * @author XiongYuFeng
 *         date 2016年5月10日 下午5:44:41
 */
public class ChangeNewPhonePresenter extends RSAPresenter<ChangeNewPhoneModel, ChangeNewPhonePresenter.View> {
	private static final String TAG = ChangeNewPhonePresenter.class.getSimpleName();
	private View mView;

	public static class Generator implements PresenterFactory<ChangeNewPhonePresenter> {
		@Override
		public ChangeNewPhonePresenter create() {
			return new ChangeNewPhonePresenter();
		}
	}

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new ChangeNewPhoneModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {

		ChangeNewPhoneModel.ChangePhoneNumParams getChangePhoneNumParams();

		void changePhoneSuccess();

		void changePhoneFailure(String tips);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		ChangeNewPhoneModel.ChangePhoneNumParams changePhoneNum = (ChangeNewPhoneModel.ChangePhoneNumParams) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		changePhoneNum.loginName = RSA.encryptByPublicKey(changePhoneNum.loginName, keyRSA);
		changePhoneNum.phone = RSA.encryptByPublicKey(changePhoneNum.phone, keyRSA);
		return changePhoneNum;
	}

	public void changePhoneNum() {
		CLog.i(TAG, "修改手机号参数-->" + mView.getChangePhoneNumParams().toString());
		execute(mView.getChangePhoneNumParams(), FUNCTIONAL_CODE, true, null, null);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void changePhoneNumResult(ChangeNewPhoneModel.ChangePhoneNumResult result) {
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_E025, result.getStatus());
		if (isResponseSuccess(result)) {
			mView.changePhoneSuccess();
		} else if (isResponseWarning(result)) {
			if (result.getContent() != null && "10008".equals(result.getContent().code)) {
				mView.changePhoneFailure("验证码错误");
			} else {
				mView.changePhoneFailure(TextUtils.isEmpty(result.getMsg()) ? "更改手机号失败!" : result.getMsg());
			}
		} else {
			mView.changePhoneFailure(TextUtils.isEmpty(result.getMsg()) ? "更改手机号失败!" : result.getMsg());
		}
	}
}
